package com.candy.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class RedisCacheConfig {
    @Autowired
    RedisConnectionFactory connectionFactory;

    @Bean
    RedisCacheManager redisCacheManager(){
//        存放缓存配置
        Map<String, RedisCacheConfiguration> configMap=new HashMap<>();
        RedisCacheConfiguration redisCacheConfig=
                RedisCacheConfiguration.defaultCacheConfig()
                        .prefixKeysWith("qst") //key的前缀
                        .disableCachingNullValues() //禁止缓存null
                        .entryTtl(Duration.ofMinutes(30)); //缓存过期时间
//        key表示缓存名字，value表示缓存配置
        configMap.put("c1",redisCacheConfig);
        RedisCacheWriter cacheWriter=RedisCacheWriter.lockingRedisCacheWriter(connectionFactory);
        RedisCacheManager redisCacheManager=
                new RedisCacheManager(
                        cacheWriter,
                        RedisCacheConfiguration.defaultCacheConfig(),
                        configMap);
        return redisCacheManager;

    }
}